
/**
 * Project Name:cats-web
 * File Name:WebInitializer.java
 * Package Name:com.catsic.core.web.actions
 * Date:2014年3月4日下午3:12:12
 * Copyright (c) 2014, oa.catsic.com All Rights Reserved.
 */
 
package com.catsic.web;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import ch.qos.logback.ext.spring.web.LogbackConfigListener;


/**
 * ClassName: WebInitializer
 * Description: 替代系统中传统的web.xml配置
 * date: 2014年3月4日 下午3:12:12
 * author: yangyd
 */
public class WebInitializer implements WebApplicationInitializer {

	/**
	 * 添加listener、servlet
	 * @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext)
	 */
	@Override 
	public void onStartup(ServletContext servletContext)
			throws ServletException {
		/**添加ContextLoaderListener*/
		AnnotationConfigWebApplicationContext rootCtx = new AnnotationConfigWebApplicationContext();
		rootCtx.scan("com.catsic.base.config");
		
		servletContext.addListener(new ContextLoaderListener(rootCtx));
		
		servletContext.addListener(new LogbackConfigListener());
		
		/**
		 * 编码过滤器
		 */
		FilterRegistration.Dynamic characterEncodingFilter=servletContext.addFilter("characterEncodingFilter", new CharacterEncodingFilter());  
		//EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE)
		characterEncodingFilter.setInitParameter("forceEncoding", "false");  
		characterEncodingFilter.setInitParameter("encoding", "UTF-8");  
		characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*"); 
		
		/**
		 * 懒加载过滤器
		 */
		FilterRegistration.Dynamic openEntityManagerInViewFilter=servletContext.addFilter("openEntityManagerInViewFilter", new OpenEntityManagerInViewFilter());  
		openEntityManagerInViewFilter.addMappingForUrlPatterns(null, false, "/*"); 
		
		/**添加DispatcherServlet*/
		ServletRegistration.Dynamic dispatcher =
				servletContext.addServlet("catsic", new DispatcherServlet(rootCtx));
		dispatcher.setLoadOnStartup(1);
		dispatcher.addMapping("/");
		
		/**添加XFireSpringServlet*/
/*		ServletRegistration.Dynamic dispatcherXfire = servletContext.addServlet("/wservice", new XFireSpringServlet());
		dispatcherXfire.setLoadOnStartup(2);
		dispatcherXfire.addMapping("/services/*");*/
		
	}

}
